<template>
  <div>
    <el-button type="primary" @click="pasteData">粘贴数据</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      startRow: 0, // 起始行索引
      startColumn: 0, // 起始列索引
    };
  },
  methods: {
    // 将复制的数据粘贴到表格中
    pasteData() {
      navigator.clipboard.readText().then((data) => {
        console.log(data);
        const rows = data.split("\n");
        console.log(rows)
        const headers = rows[0].split("\t");
        console.log(headers)
        const tableData = [...this.tableData];
        let rowIndex = this.startRow;
        for (let i = 1; i < rows.length && rowIndex < tableData.length; i++) {
          const row = rows[i].split("\t");
          if (row.length === headers.length) {
            let columnIndex = this.startColumn;
            for (let j = 0; j < headers.length && columnIndex < tableData[rowIndex].length; j++) {
              const header = headers[j];
              if (columnIndex < tableData[rowIndex].length && tableData[rowIndex][columnIndex].prop === header) {
                tableData[rowIndex][columnIndex].value = row[j];
              }
              columnIndex++;
            }
            rowIndex++;
          }
        }
        this.tableData = tableData;
      });
    },
  },
};
</script>